<template>
  <div class="modal_table_only">
    <ProTable
      ref="tableRef"
      :fetchListApi="getDeviceRules"
      :columns="columns"
      row-key="id"
      hide-search
    >
      <template #toolbars>
        <Space>
          <b-button icon="add" @click="onAdd()" code="accessRules:add"
            >新增</b-button
          >
        </Space>
      </template>
      <template #operation="{ record }">
        <b-button
          icon="edit"
          type="link"
          @click="onView(record)"
          code="accessRules:update"
          >编辑</b-button
        >
        <b-button
          icon="delete"
          type="link"
          @click="onDelete(record)"
          code="accessRules:del"
          >删除</b-button
        >
      </template>
    </ProTable>
  </div>
  <FormModal :items="items">
    <template #intervalMatchArray="{ formState }">
      <FormItemRest>
        <Row :gutter="8">
          <Col :span="8">
            <Input
              v-model:value="formState.intervalMatchArray[0]"
              placeholder="请输入前缀"
            />
          </Col>
          <Col :span="1" class="flex justify-center items-center"></Col>
          <Col :span="7">
            <Input
              v-model:value="formState.intervalMatchArray[1]"
              placeholder="请输入区间范围开始数字"
            />
          </Col>
          <Col :span="1" class="flex justify-center items-center">~</Col>
          <Col :span="7">
            <Input
              v-model:value="formState.intervalMatchArray[2]"
              placeholder="请输入区间范围结束数字"
            />
          </Col>
        </Row>
      </FormItemRest>
    </template>
  </FormModal>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import {
  Col,
  FormItemRest,
  Input,
  Modal,
  Row,
  Space,
  message,
} from 'ant-design-vue';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import {
  addDeviceRules,
  delDeviceRules,
  getDeviceRules,
  updateDeviceRules,
} from '@/api/device';

defineOptions({
  name: 'Rules',
});

interface Props {
  projectData: Array<any>;
}
const props = defineProps<Props>();

const tableRef = ref();
const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '精确匹配',
    dataIndex: 'direct',
  },
  {
    title: '通配符匹配',
    dataIndex: 'topic',
  },
  {
    title: '区间匹配',
    dataIndex: 'intervalMatch',
  },
  {
    title: '项目名称',
    dataIndex: 'projectName',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    fixed: 'right',
    width: 150,
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '精确匹配',
    type: 'select',
    field: '_direct',
    props: {
      placeholder: '请输入精确匹配',
      mode: 'tags',
      tokenSeparators: [','],
      open: false,
    },
  },
  {
    label: '通配符匹配',
    type: 'input',
    field: 'topic',
    props: {
      placeholder: '请输入通配符匹配',
    },
  },
  {
    label: '区间匹配',
    type: 'input',
    field: 'intervalMatchArray',
    rules: [
      {
        message: '请输入正确格式的区间规则,区间范围请填写纯数字',
        validator(rule, value, callback) {
          if ((value[1] && isNaN(value[1])) || (value[2] && isNaN(value[2]))) {
            return Promise.reject('请输入正确格式的区间规则');
          }
          return Promise.resolve();
        },
        trigger: 'blur',
      },
    ],
  },
  {
    label: '所属项目',
    type: 'treeSelect',
    field: 'projectId',
    rules: [
      {
        required: true,
        message: '请选择所属项目',
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请选择所属项目',
      treeData: props.projectData,
      fieldNames: {
        value: 'id',
      },
    },
  },
]);
const { FormModal, open } = useFormModal({
  size: 'middle',
  column: 1,
  formProps: { labelCol: { span: 3 } },
});
const onAdd = () => {
  const _direct: any = [];
  const intervalMatchArray = ['', '', ''];
  open({
    title: '新增',
    defaultValue: { _direct, intervalMatchArray },
    serviceApi: async (params: any): Promise<any> => {
      const direct = params._direct.join();
      const intervalMatch = params.intervalMatchArray.join('-');
      await addDeviceRules({ ...params, direct, intervalMatch });
      tableRef.value.refresh();
    },
  });
};
const onView = (record: any) => {
  const _direct = record.direct ? record.direct.split(',') : [];
  const intervalMatchArray = record.intervalMatch
    ? record.intervalMatch.split('-')
    : ['', '', ''];
  open({
    title: '编辑',
    defaultValue: { ...record, _direct, intervalMatchArray },
    serviceApi: async (params: any): Promise<any> => {
      const direct = params._direct.join();
      const intervalMatch = params.intervalMatchArray.join('-');
      await updateDeviceRules({ ...params, direct, intervalMatch });
      tableRef.value.refresh();
    },
  });
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};
const onDelete = async (record: any) => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `是否确认删除当前项？`,
    onOk: async () => {
      await delDeviceRules(record.id);
      sleep(() => tableRef.value.refresh());
      message.success('操作成功');
    },
  });
};
</script>
